import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
const _ = cloud.database().command
export default async function (ctx: FunctionContext) {
  let body = ctx.body
  /**
   * {
   *     "id": "",
   *     "couponType": "CASH",
   *     "couponName": "三生鼎",
   *     "amount": "0",
   *     "conditionAmount": "0",
   *     "startTime": "2023-11-26",
   *     "endTime": "2023-11-30",
   *     "rangeType": "ALL",
   *     "rangeDesc": "",
   *     "publishCount": "121",
   *     "perLimit": "1",
   *     "useCount": "0",
   *     "receiveCount": "",
   *     "expireTime": "2023-11-30 00:00:00",
   *     "publishStatus": ""
   * }
   */

  if (nw.util.isNull(body.couponName)){
    return fail("优惠券名称不能为空")
  }
  if (nw.util.isNull(body.couponType)){
    return fail("优惠券类型不能为空")
  }
  //校验类型-名称是否重复
  let count = await nw.db.count({
    dbName:"couponInfo",
    whereJson:{deleted:0,couponType:_.eq(body.couponType),couponName:_.eq(body.couponName)}
  })
  if (count>0){
    return fail("优惠券重复")
  }
  //构建保存结果
  let data = {
    couponType : body.couponType,
    couponName : body.couponName,
    amount : body.amount || 0,
    conditionAmount : body.conditionAmount || 0,
    startTime : body.startTime,
    endTime : body.endTime,
    rangeType : body.rangeType||1,
    rangeDesc : body.rangeDesc,
    publishCount : body.publishCount||1,
    perLimit : body.perLimit ||1,
    useCount : body.useCount ||0,
    receiveCount : body.receiveCount ||0,
    expireTime : body.expireTime,
    publishStatus : body.publishStatus ||0,
    createTime:new Date(),
    updateTime:new Date(),
    deleted:0
  }

  let id = await nw.db.add({
    dbName:"couponInfo",
    dataJson:data
  })
  if (nw.util.isNull(id)){
    return fail("保存失败")
  }
  return ok("保存成功")

}
